<template>
  <div class="app-container">
    <template v-for="(board, index) of boardList">
      <div
        :key="board.id"
        :class="`line-chart-container${index}`"
        :style="{height:'500px',width:'100%',minWidth:'653px'}"
      >
        <div class="line-chart-top-container">
          <el-row>
            <el-col
              class="drop-item"
              :xs="{offset:1,span:3}"
              :sm="{offset:1,span:3}"
              :md="{offset:2,span:3}"
              :lg="{offset:3,span:3}"
              style="min-width: 100px;"
            >
              <el-select v-model="durTypeList[index]" placeholder="请选择" style="width: 150px;">
                <el-option
                  v-for="item in options"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col
              :xs="{offset:1,span:6}"
              :sm="{offset:2,span:6}"
              :md="{offset:3,span:6}"
              :lg="{offset:3,span:6}"
              style="min-width: 240px;"
            >
              <el-radio-group v-model="timeRangeList[index]">
                <el-radio label="1" class="time-radio">1天内</el-radio>
                <el-radio label="3" class="time-radio">3天内</el-radio>
                <el-radio label="7" class="time-radio">7天内</el-radio>
              </el-radio-group>
            </el-col>
            <el-col
              :xs="{offset:0,span:2}"
              :sm="{offset:0,span:2}"
              :md="{offset:2,span:2}"
              :lg="{offset:2,span:2}"
              style="min-width: 90px;"
            >
              <el-input v-model="timeRangeList[index]">
                <template slot="append" style="padding: 0;">
                  <span class="el-radio__label">天内</span>
                </template>
              </el-input>
            </el-col>
            <el-col
              :xs="{offset:0,span:3}"
              :sm="{offset:0,span:3}"
              :md="{offset:1,span:3}"
              :lg="{offset:1,span:3}"
              style="min-width: 150px;"
            >
              <el-button v-loading="operLoadingList[index]" type="primary" :disabled="isDisable(index)" @click="handleSearch(index)">查询</el-button>
              <el-button v-loading="operLoadingList[index]" type="danger" :disabled="isDisable(index)" @click="handleDelBoard(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <div class="line-chart-main-container">
          <line-chart :ref="`chart${index}`" :class-name="'Chart' + index" />
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import resize from '@/components/Charts/mixins/resize'
import { delBoard, getBoardList, getQuotaData } from '@/api/board'
import { parseTime } from '@/utils'
import LineChart from '@/views/board/components/LineChart'

export default {
  name: 'ListBoard',
  components: {
    LineChart
  },
  mixins: [resize],
  data() {
    return {
      idx: 0,
      idx1: 0,
      boardList: [],
      paramList: [],
      durTypeList: [],
      timeRangeList: [],
      quotaDataList: [],
      chartList: [],
      operLoadingList: [],
      options: [
        { key: 1, value: '1', label: '间隔1分钟' },
        { key: 2, value: '2', label: '间隔1小时' },
        { key: 3, value: '3', label: '间隔1天' }
      ]
    }
  },
  created() {
    getBoardList().then(async resp => {
      this.boardList = resp.data.list
      for (let i = 0; i < this.boardList.length; i++) {
        this.operLoadingList.push(false)
      }
      // console.log('boardList', this.boardList)
    })
  },
  mounted() {
    // 请求数据
    const a = setInterval(async() => {
      if (this.idx >= this.boardList.length) clearInterval(a)
      else {
        const board = this.boardList[this.idx]
        const end = Date.now()
        const beg = end - 1000 * 3600 * 24
        const data = {
          end: parseTime(end),
          beg: parseTime(beg),
          type: 2,
          boardId: board.id
        }
        if (!this.paramList[this.idx]) {
          this.paramList.push(Object.assign({}, data))
          this.durTypeList.push('2')
          this.timeRangeList.push('1')
        } else {
          await getQuotaData(data).then(resp => {
            if (resp.code === 200) {
              const boardData = resp.data.boardData
              this.quotaDataList.push(boardData)
              this.idx += 1
            }
          })
        }
      }
    }, 1000)
    // 绘图
    const b = setInterval(async() => {
      if (this.idx1 >= this.boardList.length) clearInterval(b)
      else {
        const quotaData = this.quotaDataList[this.idx1]
        if (quotaData) {
          const ref = this.$refs[`chart${this.idx1}`]
          // console.log('quotaData', quotaData)
          // console.log('ref', ref, typeof ref, ref[0])
          ref[0].updateOptions(quotaData.xdata, quotaData.series, quotaData.name, quotaData.unit)
          this.chartList.push(ref[0])
          this.idx1 += 1
        }
      }
    }, 1000)
  },
  methods: {
    async handleSearch(index) {
      const res = this.getTimeRange(this.timeRangeList[index])
      if (typeof res === 'string') this.$message.error(res)
      else {
        this.paramList[index].beg = res.beg
        this.paramList[index].end = res.end
        this.paramList[index].type = this.durTypeList[index]
        // console.log('param', this.paramList[index])
        await getQuotaData(this.paramList[index]).then(resp => {
          if (resp.code === 200) {
            const quotaData = resp.data.boardData
            const ref = this.$refs[`chart${index}`]
            // console.log('btn quotaData', quotaData)
            // console.log('ref', ref, typeof ref, ref[0])
            ref[0].updateOptions(quotaData.xdata, quotaData.series, quotaData.name, quotaData.unit)
          }
        })
      }
    },
    handleDelBoard(index) {
      this.$confirm('此操作将删除该视图, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const board = this.quotaDataList[index]
        const data = { name: board.name, quotaName: board.quotaName, unit: board.unit }
        const ref = this.$refs[`chart${index}`]
        // console.log('btn quotaData', quotaData)
        // console.log('ref', ref, typeof ref, ref[0])
        console.log('data', data, ref)
        this.operLoadingList[index] = true
        delBoard(data).then(resp => {
          if (resp.code === 200) {
            this.$message.success('删除视图成功')
            this.chartList[index].destroyChart()
            const con = document.getElementsByClassName(`line-chart-container${index}`)
            con[0].remove()
            this.boardList.splice(index, 1)
            this.paramList.splice(index, 1)
            this.durTypeList.splice(index, 1)
            this.timeRangeList.splice(index, 1)
            this.quotaDataList.splice(index, 1)
            this.chartList.splice(index, 1)
            this.operLoadingList.splice(index, 1)
          }
        })
      }).catch(() => {
        // 点击取消进行的操作
      })
    },
    getTimeRange(newVal) {
      let end = new Date().getTime()
      let dur = 0
      if (isNaN(newVal)) return '不是数字'
      newVal = parseInt(newVal)
      if (!Number.isInteger(newVal)) return '不是整数'
      if (newVal <= 30) dur += 1000 * 60 * 60 * 24 * newVal
      else return '数值太大'
      let beg = end - dur
      beg = parseTime(beg)
      end = parseTime(end)
      // console.log('timeRange', beg, end)
      return { beg, end }
    },
    getOptions(xData, series) {
      // console.log('xdata, series', xData, series)
      const tmpSeries = []
      const tmpLegend = []
      for (const s of series) {
        const name = `设备号:${s.number};指标ID:${s.quotaId}`
        tmpLegend.push(name)
        tmpSeries.push({
          data: s.data,
          name: name,
          type: 'line',
          smooth: true
        })
      }
      return {
        tooltip: { trigger: 'axis' },
        legend: { data: tmpLegend },
        grid: { top: '4%', left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xData
        },
        yAxis: {
          type: 'value',
          axisTick: {
            show: false
          }
        },
        series: tmpSeries
      }
    },
    isDisable(index) {
      if (this.chartList[index]) return false
      else return true
    }
  }
}
</script>

<style lang="scss" scoped>

.app-container {
  width: 100%;

  .line-chart-top-container {
    height: 50px;
    width: 100%;

    .time-radio {
      margin: 10px 10px;
    }
  }

  .line-chart-main-container {
    height: 350px;
    width: 100%;
  }
}

::v-deep .el-input__inner {
  padding: 0 5px;
}

::v-deep .el-input-group__append {
  background-color: #F5F7FA;
  color: #909399;
  vertical-align: middle;
  display: table-cell;
  position: relative;
  border: 1px solid #DCDFE6;
  border-left-color: rgb(220, 223, 230);
  border-radius: 4px;
  padding: 0 7px;
  width: 1px;
  white-space: nowrap;
}

::v-deep .el-radio__label {
  font-size: 14px;
  padding-left: 4px;
}

.drop-item {
  ::v-deep .el-input {
    border: #1f2d3d 1px;
    padding: 0 5px;
    width: 110px;

    ::v-deep .el-input__inner {
      padding: 0 10px;
    }

    ::v-deep .el-radio__label {
      font-size: 14px;
      padding-left: 4px;
    }
  }
}
</style>
